#include "StdAfx.h"
#include "SerThread.h"


CSerThread::CSerThread(void)
{
	m_pThread = NULL;
}

CSerThread::~CSerThread(void)
{
}

void CSerThread::Run()
{
	if(m_socket)
	{
		int nRet = ::select(0, &fdSocket, NULL, NULL, NULL);
		if(nRet > 0)
		{
			for(int i=0; i<(int)fdSocket.fd_count; i++)
			{
				if(FD_ISSET(fdSocket.fd_array[i], &fdSocket))
				{
						char szText[256] = {0};
						m_cs.lock();
						int nRecv = ::recv(fdSocket.fd_array[i], szText, 256, 0);
						m_cs.unlock();
						if(nRecv<=0)
						{
							::closesocket(fdSocket.fd_array[i]);
							FD_CLR(fdSocket.fd_array[i], &fdSocket);
						}else{
							m_pThread->Send(szText,nRecv);
						}
				}
			}
		}
	}
}

void CSerThread::Send(char *buf,int len)
{
	m_cs.lock();

	::send(m_socket,buf,len,0);

	m_cs.unlock();
}

void CSerThread::Connect(CThread *pThread)
{
	m_pThread = pThread;
	pThread->m_pThread = this;
}

void CSerThread::Init(SOCKET socket)
{
	m_socket = socket;
	FD_ZERO(&fdSocket);
	FD_SET(m_socket,&fdSocket);
}